from flask import jsonify, request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from app.api.auth import bp
from app.models.user import User
from app.extensions import db

@bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    # 检查用户是否存在
    user = User.query.filter_by(username=username).first()
    
    # 用户不存在
    if not user:
        return jsonify({'message': '用户未注册，请先注册'}), 403
    
    # 密码验证
    if user.check_password(password):
        access_token = create_access_token(identity=user.id)
        
        # 更新最后登录时间
        user.last_login = db.func.now()
        db.session.commit()
        
        return jsonify({
            'token': access_token,
            'user': user.to_dict()
        })
    
    # 密码错误
    return jsonify({'message': '密码错误'}), 401

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    
    # 参数验证
    if not all([username, password, email]):
        return jsonify({'message': '用户名、密码和邮箱都不能为空'}), 400
    
    # 检查用户名是否已存在
    if User.query.filter_by(username=username).first():
        return jsonify({'message': '用户名已存在'}), 400
    
    # 检查邮箱是否已存在
    if User.query.filter_by(email=email).first():
        return jsonify({'message': '邮箱已被注册'}), 400
    
    # 创建新用户
    user = User(
        username=username,
        email=email
    )
    user.set_password(password)
    
    try:
        db.session.add(user)
        db.session.commit()
        return jsonify({'message': '注册成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'注册失败: {str(e)}'}), 500

@bp.route('/user-info', methods=['GET'])
@jwt_required()
def get_user_info():
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)
    return jsonify(user.to_dict())